package yxy.game.pm2.command.player;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.Sign;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PlayerMessage;

/** 玩家 修改形象 */
@MessageType(proto = Command.PlayerAvatarChange, classtype = PlayerMessage.PlayerAvatarChangeRequest.class)
public class CMD_PlayerAvatarChange extends Command<PlayerMessage.PlayerAvatarChangeRequest> {

	@Override
	public void execute(MessageSource messageSource, PlayerMessage.PlayerAvatarChangeRequest request) {
		String playerCode = messageSource.getTag();
		int avatar = request.getAvatar();

		PlayerMessage.PlayerAvatarChangeResponse.Builder response = PlayerMessage.PlayerAvatarChangeResponse.newBuilder();

		if (avatar > 0 && !Sign.exist(playerCode, CurrencyType.CT_形象, avatar)) {
			send(messageSource, response, Result.PlayerAvatarNotGet);
			return;
		}
		PlayerBean playerBean = PlayerBean.get(playerCode);
		try {
			if (playerBean.tryLock()) {
				playerBean.setAvatar(avatar);
				playerBean.set();

				response.setAvatar(playerBean.getAvatar());
				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			playerBean.unlock();
		}

	}

	private void send(MessageSource messageSource, PlayerMessage.PlayerAvatarChangeResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}